package com.ttg.web.service.Impl;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ttg.common.entities.BasePage;
import com.ttg.common.entities.BaseResult;
import com.ttg.common.enums.*;
import com.ttg.common.exception.BaseException;
import com.ttg.common.utils.DateTimeUtil;
import com.ttg.model.dto.*;
import com.ttg.model.dto.VipTagDto;
import com.ttg.model.dto.open.*;


import com.ttg.model.pojo.*;
import com.ttg.model.vo.*;
import com.ttg.model.vo.VipTagVo;
import com.ttg.model.vo.open.*;
import com.ttg.web.dao.*;
import com.ttg.web.service.GradeToCouponService;
import com.ttg.web.service.VipBankInfoManagementService;
import com.ttg.web.service.VipInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @author zhangHongYuan
 * @description
 * @date 2023/6/8 11:19
 */
@Service
public class VipInfoServiceImpl implements VipInfoService {

    @Autowired
    private VipInfoDao vipInfoDao;

    @Autowired
    private VipGrowDetailDao vipGrowDetailDao;

    @Autowired
    private VipBindAccountDao vipBindAccountDao;


    @Autowired
    private VipBindMerchantDao vipBindMerchantDao;

    @Autowired
    private VipMctInfoDao vipMctInfoDao;

    @Autowired
    private VipBankInfoManagementService vipBankInfoManagementService;

    @Autowired
    private VipGradeConfigDao vipGradeConfigDao;

    @Autowired
    private RulesListDao rulesListDao;

    @Autowired
    private TagInfoDao tagInfoDao;

    @Autowired
    private BankPublicPrimitiveDao bankPublicPrimitiveDao;

    @Autowired
    private BankCardDataInfoDao bankCardDataInfoDao;

    @Autowired
    private VipBindTagDao vipBindTagDao;

    @Autowired
    private TaskInfoDao taskInfoDao;

    @Autowired
    private VipBindPeopleDao vipBindPeopleDao;

    @Autowired
    private GradeToCouponService gradeToCouponService;

    @Override
    public BaseResult getList(VipInfoListGetDto dto) {

        BasePage<Object> parse = dto.parse();
        BasePage<VipInfoGetListVo> page = new BasePage<>(parse.getCurrent(), parse.getSize(), parse.getTotal(), parse.isSearchCount());
        BasePage<VipInfoGetListVo> voBasePage = vipInfoDao.getList(page, dto.getVipId(), dto.getVipMobile(), dto.getVipName(), dto.getVipGrade(),dto.getVipStatus(), dto.getStartTime(), dto.getEndTime());
        if (Objects.nonNull(voBasePage)&&!CollectionUtils.isEmpty(voBasePage.getList())){
            for (VipInfoGetListVo vipInfoGetListVo : voBasePage.getList()) {
                vipInfoGetListVo.setVipBindAccountNum(""+bankCardDataInfoDao.countByCstId(vipInfoGetListVo.getVipCstId()));
                vipInfoGetListVo.setVipBindTagNum(""+vipBindTagDao.countTagByVipId(Long.valueOf(vipInfoGetListVo.getVipId())));
            }
        }
        return BaseResult.success(voBasePage);
    }

    @Override
    public BaseResult getInfoList(VipGetInfoListDto dto) {
        List<Long> vipIds = new ArrayList<>();
        if (!Objects.isNull(dto.getPepId())) {
            vipIds = vipBindPeopleDao.selectByPepId(dto.getPepId());
        }
        BasePage<Object> parse = dto.parse();
        BasePage<VipGetInfoListVo> page = new BasePage<>(parse.getCurrent(), parse.getSize(), parse.getTotal(), parse.isSearchCount());
        BasePage<VipGetInfoListVo> voBasePage = vipInfoDao.getInfoList(page, dto.getVipId(), dto.getVipMobile(), dto.getVipStatus(), vipIds);
        //TODO 后续需要将这段逻辑写入数仓同步会员信息中
        ArrayList<VipGetInfoListVo> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(voBasePage.getList())) {
            for (VipGetInfoListVo vipGetInfoListVo : voBasePage.getList()) {
                if (vipGetInfoListVo.getVipType().equals(1)) {
                    vipGetInfoListVo.setVipName(vipGetInfoListVo.getMctName());
                } else if (vipGetInfoListVo.getVipType().equals(2)) {
                    vipGetInfoListVo.setVipName(vipGetInfoListVo.getMctName());
                } else if (vipGetInfoListVo.getVipType().equals(3)) {
                    vipGetInfoListVo.setVipName(vipGetInfoListVo.getVipCstName());
                } else if (vipGetInfoListVo.getVipType().equals(4)) {
                    vipGetInfoListVo.setVipName("访客" + vipGetInfoListVo.getVipId());
                }
                VipGetInfoListVo vo = new VipGetInfoListVo();
                BeanUtils.copyProperties(vipGetInfoListVo, vo);
                vos.add(vo);
            }
        }
        voBasePage.setList(vos);
        return BaseResult.success(voBasePage);
    }

    @Override
    public BaseResult getOneInfo(VipGetInfoListDto dto) {
        Long vipId = dto.getVipId();
        VipInfo vipInfo = vipInfoDao.getById(vipId);
        if (Objects.isNull(vipInfo)) {
            throw new BaseException(ErrorCodeEnums.VIP_IS_NOT_EXIST);
        }
        VipGetOneVo vo = new VipGetOneVo();
        BeanUtils.copyProperties(vipInfo, vo);
        //详细地址设置为所在地
        vo.setVipAddressDetail(vipInfo.getVipAddress());
        List<VipBindTag> byVipId = vipBindTagDao.getByVipId(vipId);
        List<VipTag> vipTagList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(byVipId)) {
            for (VipBindTag vipBindTag : byVipId) {
                VipTag vipTag = new VipTag();
                vipTag.setId(vipBindTag.getTagId());
                TagInfo byId = tagInfoDao.getById(vipBindTag.getTagId());
                vipTag.setTagName(byId.getTagName());
                vipTagList.add(vipTag);
            }
        }
        vo.setVipTagList(vipTagList);
        return BaseResult.success(vo);
    }

    @Override
    public BaseResult updateVipStatus(VipUpdataDto dto) {
        if (Objects.isNull(dto.getVipId())) {
            throw new BaseException(ErrorCodeEnums.VIP_INFO_ID_IS_NULL);
        }
        if (Objects.isNull(dto.getVipStatus()) || !dto.getVipStatus().equals(0) && !dto.getVipStatus().equals(1)) {
            throw new BaseException(ErrorCodeEnums.PARAM_VALIDATION_FAIL);
        }

        vipInfoDao.updateVipStatus(dto);

//            VipInfo vipInfo = vipInfoDao.getById(dto.getVipId());
//            if (ObjectUtil.isNotNull(vipInfo)) {
//                List<VipInfo> vipInfos = new ArrayList<>();
//                vipInfos.add(vipInfo);
//                gradeToCouponService.sendToVipList(vipInfos);
//            }


        return BaseResult.success("Success");
    }

    @Override
    public BaseResult getVipTag(VipTagDto dto) {
        if (dto.getVipId()==null&& StringUtils.isEmpty(dto.getIdCard())&& StringUtils.isEmpty(dto.getBusinessLicense())){
            return BaseResult.success("SUCCESS");
        }
        VipTagVo vo = vipInfoDao.getVipTag(dto);
        if (Objects.isNull(vo)) {
            throw new BaseException(ErrorCodeEnums.VIP_IS_NOT_EXIST);
        }
        List<VipTag> vipTagList = tagInfoDao.getTagListByClass(vo.getVipId(), dto.getTagClassId());
        vo.setVipTagList(vipTagList);
        return BaseResult.success(vo);
    }


    @Override
    public BaseResult editVip(VipInfoEditDto dto) {
        if (Objects.isNull(dto)) {
            throw new BaseException(ErrorCodeEnums.PARAM_IS_NULL);
        }
        if (StringUtils.isBlank(dto.getVipId())) {
            throw new BaseException(ErrorCodeEnums.VIP_INFO_ID_IS_NULL);
        }
        VipInfo vipInfo = vipInfoDao.getById(dto.getVipId());
        if (Objects.isNull(vipInfo)) {
            throw new BaseException(ErrorCodeEnums.VIP_IS_NOT_EXIST);
        }
        if (Objects.nonNull(dto.getVipGradeDate())) {
            LocalDate localDate = LocalDate.parse(dto.getVipGradeDate());
            if (LocalDate.now().isAfter(localDate)) {
                throw new BaseException(ErrorCodeEnums.DATE_IS_ERROR);
            }
            if (Objects.nonNull(vipInfo.getVipGradeStartDate())) {
                if (localDate.isBefore(vipInfo.getVipGradeStartDate())) {
                    throw new BaseException(ErrorCodeEnums.END_DATE_IS_ERROR);
                }
            }
            vipInfo.setVipGradeDate(localDate);
        }
        BeanUtils.copyProperties(dto, vipInfo);
        if (StringUtils.isNotBlank(dto.getVipSex())) {
            vipInfo.setVipSex(Integer.valueOf(dto.getVipSex()));
        }
        vipInfo.setVipId(Long.valueOf(dto.getVipId()));
        vipInfo.setVipStatus(dto.getVipStatus());

        if (vipInfoDao.updateById(vipInfo)) return BaseResult.success("Success");
        return BaseResult.defaultFail();
    }

    @Override
    public BaseResult deleteVip(VipInfoDeleteDto dto) {
        if (Objects.isNull(dto)) {
            throw new BaseException(ErrorCodeEnums.PARAM_IS_NULL);
        }
        if (StringUtils.isBlank(dto.getVipId())) {
            throw new BaseException(ErrorCodeEnums.VIP_INFO_ID_IS_NULL);
        }
        if (vipInfoDao.removeById(dto.getVipId())) return BaseResult.success("Success");
        return BaseResult.defaultFail();
    }


    @Override
    @Transactional
    public BaseResult editVipType(EditVipTypeDto dto) {
        if (Objects.isNull(dto)) {
            throw new BaseException(ErrorCodeEnums.PARAM_IS_NULL);
        }
        if (StringUtils.isBlank(dto.getCardNo())) {
            throw new BaseException(ErrorCodeEnums.VIP_CRD_ID_NO_IS_NULL);
        }
        if (ObjectUtil.isEmpty(dto.getMctNo())) {
            throw new BaseException(ErrorCodeEnums.MERCHANT_NO_IS_NULL);
        }
        if (StringUtils.isBlank(dto.getMctName())) {
            throw new BaseException(ErrorCodeEnums.MERCHANT_NAME_IS_NULL);
        }
        VipInfo vipInfo = vipInfoDao.openGetByCrdIdNo(dto.getCardNo());
        if (ObjectUtil.isEmpty(vipInfo)) {
            throw new BaseException(ErrorCodeEnums.VIP_IS_NOT_EXIST);
        }
//        if (vipInfoDao.updateTypeByCrdIdNo(dto.getCardNo(), VipTypeEnum.MCT_VIP.getCode())) {
//            VipBindMerchant vipBindMerchant = new VipBindMerchant();
//            vipBindMerchant.setVipId(vipInfo.getVipId());
//            vipBindMerchant.setMctName(dto.getMctName());
//            vipBindMerchant.setMctNo(dto.getMctNo());
//            vipBindMerchant.setBindTime(LocalDateTime.now());
//            vipBindMerchant.setUpdateTime(LocalDateTime.now());
//            if (vipBindMerchantDao.save(vipBindMerchant)) return BaseResult.success(new EditVipTypeVo("SUCCESS"));
//        }
        return BaseResult.defaultFail();
    }

    @Override
    public BaseResult getVipInfo(GetVipInfoDto dto) {
        if (Objects.isNull(dto)) {
            throw new BaseException(ErrorCodeEnums.PARAM_IS_NULL);
        }
        if (StringUtils.isBlank(dto.getCrdIdNo())) {
            throw new BaseException(ErrorCodeEnums.VIP_CRD_ID_NO_IS_NULL);
        }
        VipInfo vipInfo = vipInfoDao.openGetByCrdIdNo(dto.getCrdIdNo());
        if (Objects.isNull(vipInfo)) {
            throw new BaseException(ErrorCodeEnums.VIP_IS_NOT_EXIST);
        }
        GetVipInfoVo getVipInfoVo = new GetVipInfoVo();
        getVipInfoVo.setVipMobile(vipInfo.getVipPhoneNumber());
        getVipInfoVo.setVipName(vipInfo.getVipCstName());
        getVipInfoVo.setVipGrade(String.valueOf(vipInfo.getVipGrade()));
//        getVipInfoVo.setVipGrowthValue(String.valueOf(vipInfo.getVipNowGrow()));


        return BaseResult.success(getVipInfoVo);
    }

    @Override
    public BaseResult getVipGrowDetail(VipDetailDto vipDetailDto) {
        if (StringUtils.isBlank(vipDetailDto.getVipId())) {
            throw new BaseException(ErrorCodeEnums.VIP_INFO_ID_IS_NULL);
        }
        BasePage<Object> parse = vipDetailDto.parse();
        BasePage<VipGrowDetail> page = new BasePage<>(parse.getCurrent(), parse.getSize(), parse.getTotal(), parse.isSearchCount());
        BasePage<VipGrowDetail> pageInfo = vipGrowDetailDao.getVipGrowDetail(page, vipDetailDto);
        BasePage<VipGrowDetailDto> basePage = new BasePage<>();
        basePage.setPagesRes(pageInfo.getPagesRes());
        List<VipGrowDetailDto> vipGrowDetailDtos = new ArrayList<>();
        List<VipGrowDetail> list = pageInfo.getList();
        if (!CollectionUtils.isEmpty(list)) {
            for (VipGrowDetail vipGrowDetail : list) {
                VipGrowDetailDto vipGrowDetailDto = new VipGrowDetailDto();
                BeanUtils.copyProperties(vipGrowDetail, vipGrowDetailDto);
//                vipGrowDetailDto.setGrowNum(vipGrowDetail.getGrowNum() + "");
                vipGrowDetailDtos.add(vipGrowDetailDto);
            }
        }
        basePage.setList(vipGrowDetailDtos);
        return BaseResult.success(basePage);
    }

    @Override
    public BaseResult getVipIntegralDetail(VipDetailDto vipDetailDto) {
        if (StringUtils.isBlank(vipDetailDto.getVipId())) {
            throw new BaseException(ErrorCodeEnums.VIP_INFO_ID_IS_NULL);
        }
        BasePage<Object> parse = vipDetailDto.parse();
        BasePage<VipGrowDetail> page = new BasePage<>(parse.getCurrent(), parse.getSize(), parse.getTotal(), parse.isSearchCount());
        BasePage<VipGrowDetail> pageInfo = vipGrowDetailDao.getVipIntegralDetail(page, vipDetailDto);
        BasePage<VipIntegralDetailDto> basePage = new BasePage<>();
        basePage.setPagesRes(pageInfo.getPagesRes());
        List<VipIntegralDetailDto> dtos = new ArrayList<>();
        List<VipGrowDetail> list = pageInfo.getList();
        if (!CollectionUtils.isEmpty(list)) {
            for (VipGrowDetail growDetail : list) {
                VipIntegralDetailDto vipIntegralDetailDto = new VipIntegralDetailDto();
                BeanUtils.copyProperties(growDetail, vipIntegralDetailDto);
                vipIntegralDetailDto.setIntegral(growDetail.getIntegral() + "");
                dtos.add(vipIntegralDetailDto);
            }
        }
        basePage.setList(dtos);
        return BaseResult.success(basePage);
    }

    @Override
    public BaseResult getVipBindAccount(VipDetailDto vipDetailDto) {
        if (StringUtils.isBlank(vipDetailDto.getVipId())) {
            throw new BaseException(ErrorCodeEnums.VIP_INFO_ID_IS_NULL);
        }
        BasePage<Object> parse = vipDetailDto.parse();
        BasePage<BankCardDataInfo> page = new BasePage<>(parse.getCurrent(), parse.getSize(), parse.getTotal(), parse.isSearchCount());
        BasePage<BankCardDataInfo> pageInfo = bankCardDataInfoDao.getVipBindAccountPage(page, vipDetailDto.getVipId());
        BasePage<VipBindAccountDto> basePage = new BasePage<>();
        basePage.setPagesRes(pageInfo.getPagesRes());
        List<VipBindAccountDto> dtos = new ArrayList<>();
        List<BankCardDataInfo> list = pageInfo.getList();
        if (!CollectionUtils.isEmpty(list)) {
            for (BankCardDataInfo vipBindAccount : list) {
                VipBindAccountDto vipBindAccountDto = new VipBindAccountDto();
                vipBindAccountDto.setId(vipBindAccount.getId());
                vipBindAccountDto.setBankAccount(vipBindAccount.getBankCardNumber());
                vipBindAccountDto.setBindTime(vipBindAccount.getAccountOpeningTime().atStartOfDay());
                vipBindAccountDto.setUpdateTime(vipBindAccount.getUpdateTime());
                dtos.add(vipBindAccountDto);
            }
        }
        basePage.setList(dtos);
        return BaseResult.success(basePage);
    }

    @Override
    public BaseResult getVipBindMerchant(VipDetailDto vipDetailDto) {
        if (StringUtils.isBlank(vipDetailDto.getVipId())) {
            throw new BaseException(ErrorCodeEnums.VIP_INFO_ID_IS_NULL);
        }
        BasePage<Object> parse = vipDetailDto.parse();
        BasePage<VipBindMerchant> page = new BasePage<>(parse.getCurrent(), parse.getSize(), parse.getTotal(), parse.isSearchCount());
        BasePage<VipBindMerchant> pageInfo = vipBindMerchantDao.getVipBindMerchantPage(page, vipDetailDto);
        BasePage<VipBindMerchantDto> basePage = new BasePage<>();
        basePage.setPagesRes(pageInfo.getPagesRes());
        List<VipBindMerchantDto> dtos = new ArrayList<>();
        List<VipBindMerchant> list = pageInfo.getList();
        if (!CollectionUtils.isEmpty(list)) {
            for (VipBindMerchant vipBindMerchant : list) {
                VipBindMerchantDto vipBindMerchantDto = new VipBindMerchantDto();
                BeanUtils.copyProperties(vipBindMerchant, vipBindMerchantDto);
                dtos.add(vipBindMerchantDto);
            }
        }
        basePage.setList(dtos);
        return BaseResult.success(basePage);
    }


    @Override
    public BaseResult getVipBindAccountDetail(VipDetailDto vipDetailDto) {
        if (StringUtils.isBlank(vipDetailDto.getVipId())) {
            throw new BaseException(ErrorCodeEnums.VIP_INFO_ID_IS_NULL);
        }

        BasePage<Object> parse = vipDetailDto.parse();
        BasePage<VipBindAccountVO> page = new BasePage<>(parse.getCurrent(), parse.getSize(), parse.getTotal(), parse.isSearchCount());

        BasePage<VipBindAccountVO> pageInfo = bankCardDataInfoDao.getVipBindCardPage(page,vipDetailDto.getVipId());
        return BaseResult.success(pageInfo);
    }

    @Override
    public BaseResult getVipBindMerchantDetail(VipDetailDto vipDetailDto) {
        if (StringUtils.isBlank(vipDetailDto.getVipId())) {
            throw new BaseException(ErrorCodeEnums.VIP_INFO_ID_IS_NULL);
        }
        BasePage<Object> parse = vipDetailDto.parse();
        BasePage<VipBindMerchantDetailVO> page = new BasePage<>(parse.getCurrent(), parse.getSize(), parse.getTotal(), parse.isSearchCount());
        BasePage<VipBindMerchantDetailVO> pageInfo = vipBindMerchantDao.getVipBindMerchantDetailPage(page, vipDetailDto);
        return BaseResult.success(pageInfo);
    }

    @Override
    public BaseResult queryBankInfo(QueryBankCardDto queryBankCardDto) {

        if (ObjectUtil.isEmpty(queryBankCardDto)) {
            throw new BaseException(ErrorCodeEnums.BANK_INFO_IS_NULL);
        }
        if (StringUtils.isBlank(queryBankCardDto.getVipName())) {
            throw new BaseException(ErrorCodeEnums.VIP_NAME_IS_NULL);
        }
        if (StringUtils.isBlank(queryBankCardDto.getVipMobile())) {
            throw new BaseException(ErrorCodeEnums.VIP_MOBILE_IS_NULL);
        }
        if (StringUtils.isBlank(queryBankCardDto.getCrdIdNo())) {
            throw new BaseException(ErrorCodeEnums.VIP_CARD_IS_NULL);
        }
        //todo:根据实名去银行查询个人信息 并入库贡献度会员表
        VipInfo vipInfo1 = vipInfoDao.openGetByCrdIdNo(queryBankCardDto.getCrdIdNo());
        if (Objects.isNull(vipInfo1)) {
            VipInfo vipInfo = new VipInfo();
            vipInfo.setVipPhoneNumber(queryBankCardDto.getVipMobile());
            vipInfo.setVipCstName(queryBankCardDto.getVipName());
            vipInfo.setVipRegTime(LocalDateTime.now());
            vipInfo.setVipRegType(1);
            vipInfo.setVipIdCardNo(queryBankCardDto.getCrdIdNo());
        }

        List<QueryCardVO> list = new ArrayList<>();
        QueryCardVO queryCardVO = new QueryCardVO();
        queryCardVO.setBankNo(Long.parseLong(generateAccountNumber()));
        queryCardVO.setBankName("中国工商银行");
        list.add(queryCardVO);
        QueryCardVO queryCardVO1 = new QueryCardVO();
        queryCardVO1.setBankNo(Long.parseLong(generateAccountNumber()));
        queryCardVO1.setBankName("中国工商银行");
        list.add(queryCardVO1);
        QueryCardVO queryCardVO2 = new QueryCardVO();
        queryCardVO2.setBankNo(Long.parseLong(generateAccountNumber()));
        queryCardVO2.setBankName("中国银行");
        list.add(queryCardVO2);
        return BaseResult.success(list);
    }

    @Override
    @Transactional
    public BaseResult bindBankCard(BindBankCardDto bindBankCardDto) {
        if (ObjectUtil.isEmpty(bindBankCardDto)) {
            throw new BaseException(ErrorCodeEnums.BANK_INFO_IS_NULL);
        }
        if (ObjectUtil.isEmpty(bindBankCardDto.getBankInfo())) {
            throw new BaseException(ErrorCodeEnums.PARAM_IS_NULL);
        }
        if (StringUtils.isBlank(bindBankCardDto.getVipName())) {
            throw new BaseException(ErrorCodeEnums.VIP_NAME_IS_NULL);
        }
        if (StringUtils.isBlank(bindBankCardDto.getVipMobile())) {
            throw new BaseException(ErrorCodeEnums.VIP_MOBILE_IS_NULL);
        }
        if (StringUtils.isBlank(bindBankCardDto.getCrdIdNo())) {
            throw new BaseException(ErrorCodeEnums.VIP_CARD_IS_NULL);
        }
        VipInfo vipInfo = vipInfoDao.openGetByCrdIdNo(bindBankCardDto.getCrdIdNo());
        if (ObjectUtil.isEmpty(vipInfo)) {
            vipInfo = new VipInfo();
            vipInfo.setVipPhoneNumber(bindBankCardDto.getVipMobile());
            vipInfo.setVipCstName(bindBankCardDto.getVipName());
            vipInfo.setVipIdCardNo(bindBankCardDto.getCrdIdNo());
            if (!vipInfoDao.save(vipInfo)) {
                throw new BaseException(ErrorCodeEnums.BIND_BANK_CARD_ERR);
            }
        }
        if (ObjectUtil.isNotEmpty(vipInfo)) {
            VipInfo finalVipInfo = vipInfo;
            bindBankCardDto.getBankInfo().forEach(bank -> {
                if (StringUtils.isBlank(bank.getVipBankAccount())) {
                    throw new BaseException(ErrorCodeEnums.BANK_ACCOUNT_IS_NULL);
                }
                if (StringUtils.isBlank(bank.getVipBankAccountName())) {
                    throw new BaseException(ErrorCodeEnums.BANK_NAME_IS_NULL);
                }
                VipBindAccount vipBindAccount = new VipBindAccount();
                vipBindAccount.setBankAccount(bank.getVipBankAccount());
                vipBindAccount.setActName(bank.getVipBankAccountName());
                vipBindAccount.setVipId(finalVipInfo.getVipId());
                vipBindAccount.setBindTime(LocalDateTime.now());
                vipBindAccount.setUpdateTime(LocalDateTime.now());
                vipBindAccountDao.save(vipBindAccount);
            });
            List<Long> ids = new ArrayList<>();
            ids.add(vipInfo.getVipId());
            if (vipBankInfoManagementService.startVipRating(ids)) {
                VipRatingInfoVo vipRatingInfoVo = vipBankInfoManagementService.getVipRating(vipInfo.getVipId());
                if (ObjectUtil.isNotEmpty(vipRatingInfoVo)) {
                    VipGradeInfoVO vipGradeInfoVO = new VipGradeInfoVO();
                    vipGradeInfoVO.setVipGrade(Integer.valueOf(vipRatingInfoVo.getGrade()));
                    vipGradeInfoVO.setVipGradeDate(DateTimeUtil.parseDateFormatStr(vipRatingInfoVo.getDate()));
                    vipGradeInfoVO.setVipGrowthValue(Integer.valueOf(vipRatingInfoVo.getGrowthValue()));
                    List<VipGrowDetail> vipGrowDetails = vipGrowDetailDao.getVipIntegralDetailByVipId(vipInfo.getVipId());
                    Long rental = 0L;
                    if (ObjectUtil.isNotEmpty(vipGrowDetails)) {
                        rental = vipGrowDetails.stream().mapToLong(VipGrowDetail::getIntegral).sum();
                        List<UpdateDetailVO> list = vipGrowDetails.stream().map(v -> {
                            UpdateDetailVO updateDetailVO = new UpdateDetailVO();
                            updateDetailVO.setUpdateTime(v.getUpdateTime());
                            updateDetailVO.setIntegral(v.getIntegral().longValue());
                            updateDetailVO.setRulesName(v.getTaskName());
                            updateDetailVO.setOrdNo(v.getId().toString());
                            updateDetailVO.setIuIurId(1);
                            return updateDetailVO;
                        }).collect(Collectors.toList());
                        vipGradeInfoVO.setUpdateDetail(list);
                    }
                    vipGradeInfoVO.setVipIntegrationAmount(rental);
                    return BaseResult.success(vipGradeInfoVO);
                }
            }
        }
        return BaseResult.defaultFail();
    }

    @Override
    public BaseResult merchantData(MerchantDataDto merchantDataDto) {
        if (ObjectUtil.isEmpty(merchantDataDto)) {
            throw new BaseException(ErrorCodeEnums.BANK_INFO_IS_NULL);
        }
        if (ObjectUtil.isEmpty(merchantDataDto.getMctNo())) {
            throw new BaseException(ErrorCodeEnums.BANK_INFO_IS_NULL);
        }
        VipInfo vipInfo = vipInfoDao.openGetByCrdIdNo(merchantDataDto.getCardNo());
        if (ObjectUtil.isEmpty(vipInfo)) {
            throw new BaseException(ErrorCodeEnums.VIP_IS_NOT_EXIST);
        }
        LocalDate localDate = LocalDate.now();
        VipMctInfo vipMctInfo = vipMctInfoDao.findMctInfoByMctAndDate(merchantDataDto.getMctNo(), localDate);
        if (ObjectUtil.isEmpty(vipMctInfo)) {
            vipMctInfo = new VipMctInfo();
            vipMctInfo.setMctNo(merchantDataDto.getMctNo());
            vipMctInfo.setMctName(merchantDataDto.getMctName());
            vipMctInfo.setVipId(vipInfo.getVipId().intValue());
            vipMctInfo.setTradeAmount(merchantDataDto.getTradeAmount());
            vipMctInfo.setTradeNum(merchantDataDto.getTradeNumber().longValue());
            vipMctInfo.setSettingTime(localDate);
            if (vipMctInfoDao.save(vipMctInfo)) {
                //调计算成长值接口
                return BaseResult.success(new EditVipTypeVo("SUCCESS"));
            }
        } else {
            vipMctInfo.setTradeAmount(merchantDataDto.getTradeAmount());
            vipMctInfo.setTradeNum(merchantDataDto.getTradeNumber().longValue());
            if (vipMctInfoDao.updateById(vipMctInfo)) {
                return BaseResult.success(new EditVipTypeVo("SUCCESS"));
            }
        }
        return BaseResult.defaultFail();
    }

    @Override
    public BaseResult queryVipData(QueryMerchantDataDto queryMerchantDataDto) {
        if (ObjectUtil.isEmpty(queryMerchantDataDto)) {
            throw new BaseException(ErrorCodeEnums.BANK_INFO_IS_NULL);
        }
        if (StringUtils.isBlank(queryMerchantDataDto.getCardNo())) {
            throw new BaseException(ErrorCodeEnums.VIP_CARD_IS_NULL);
        }
        VipInfo vipInfo = vipInfoDao.openGetByCrdIdNo(queryMerchantDataDto.getCardNo());
        if (ObjectUtil.isEmpty(vipInfo)) {
            throw new BaseException(ErrorCodeEnums.VIP_IS_ABSENT);
        }
        //调计算成长值接口，后续需要再做异步
        VipRatingInfoVo vipRatingInfoVo = vipBankInfoManagementService.getVipRating(vipInfo.getVipId());
        if (ObjectUtil.isNotEmpty(vipRatingInfoVo)) {
            VipGradeInfoVO vipGradeInfoVO = new VipGradeInfoVO();
            vipGradeInfoVO.setVipGrade(Integer.valueOf(vipRatingInfoVo.getGrade()));
            vipGradeInfoVO.setVipGradeDate(DateTimeUtil.parseDateFormatStr(vipRatingInfoVo.getDate()));
            vipGradeInfoVO.setVipIntegrationAmount(Long.valueOf(vipRatingInfoVo.getIntegration()));
            vipGradeInfoVO.setVipGrowthValue(Integer.valueOf(vipRatingInfoVo.getGrowthValue()));
            List<VipGrowDetail> vipGrowDetails = vipGrowDetailDao.getVipIntegralDetailByVipId(vipInfo.getVipId());

            Long rental = 0L;
            if (ObjectUtil.isNotEmpty(vipGrowDetails)) {
                rental = vipGrowDetails.stream().mapToLong(VipGrowDetail::getIntegral).sum();
                List<UpdateDetailVO> list = vipGrowDetails.stream().map(vipGrowDetail -> {
                    UpdateDetailVO updateDetailVO = new UpdateDetailVO();
                    updateDetailVO.setUpdateTime(vipGrowDetail.getUpdateTime());
                    updateDetailVO.setIntegral(vipGrowDetail.getIntegral().longValue());
                    updateDetailVO.setRulesName(vipGrowDetail.getTaskName());
                    updateDetailVO.setOrdNo(vipGrowDetail.getId().toString());
                    updateDetailVO.setIuIurId(1);
                    return updateDetailVO;
                }).collect(Collectors.toList());
                vipGradeInfoVO.setUpdateDetail(list);
            }
            vipGradeInfoVO.setVipIntegrationAmount(rental);
            return BaseResult.success(vipGradeInfoVO);
        }
        return BaseResult.defaultFail();
    }

    @Override
    public BaseResult queryVipEquity(VipEquityDTO vipEquityDTO) {
        VipInfo vipInfo = vipInfoDao.openGetByCrdIdNo(vipEquityDTO.getVipCardId());
        if (ObjectUtils.isEmpty(vipInfo)) {
            throw new BaseException(ErrorCodeEnums.VIP_IS_NOT_EXIST);
        }
        VipGradeConfig vipGradeConfig = vipGradeConfigDao.queryVipGradeDetail(vipInfo.getVipGrade(), GradeTypeEnum.TYPE_PRIVATE.getValue());
        List<VipGradeConfig> list = vipGradeConfigDao.list();
        VipEquityVO vipEquityVO = new VipEquityVO();
        BeanUtils.copyProperties(vipGradeConfig, vipEquityVO);
        List<VipDetailVO> vipDetailVOS = new ArrayList<>();
        list.forEach(gradeConfig -> {
            VipDetailVO vipDetailVO = new VipDetailVO();
            BeanUtils.copyProperties(gradeConfig, vipDetailVO);
            vipDetailVOS.add(vipDetailVO);
        });
        vipEquityVO.setOtherVipList(vipDetailVOS);
        return BaseResult.success(vipEquityVO);
    }


    @Override
    public BaseResult getRules(GetRulesDto dto) {
        return BaseResult.success(rulesListDao.getRulesIdAndName(dto.getRuleType()));
    }

    private static String generateAccountNumber() {
        Random random = new Random();
        int minDigits = 6;
        int maxDigits = 12;
        int numDigits = minDigits + random.nextInt(maxDigits - minDigits + 1);
        StringBuilder accountNumber = new StringBuilder();

        for (int i = 0; i < numDigits; i++) {
            accountNumber.append(random.nextInt(10));
        }

        return accountNumber.toString();
    }

    @Override
    public BaseResult queryVipTagByIdCard(QueryVipTagByIdCardListDto dto) {

        if (Objects.isNull(dto) || CollectionUtils.isEmpty(dto.getIdCardListDto())) {
            throw new BaseException(ErrorCodeEnums.PARAM_IS_NULL);
        }
        //限制每次查询最多1000条
        if (dto.getIdCardListDto().size()>1000){
            throw new BaseException(ErrorCodeEnums.VIP_QUERY_LIST_SIZE_ERROR);
        }

        List<QueryVipTagInfoVo> res = vipInfoDao.queryVipTagByIdCard(dto.getIdCardListDto(),CustomerTypeEnum.TYPE_PRIVATE.getValue());
        return BaseResult.success(res);
    }
    @Override
    public BaseResult queryVipTagByMctNo(QueryVipTagByMctNoListDto dto) {
        if (Objects.isNull(dto) || CollectionUtils.isEmpty(dto.getMctNos())) {
            throw new BaseException(ErrorCodeEnums.PARAM_IS_NULL);
        }

        //限制每次查询最多1000条
        if (dto.getMctNos().size()>1000){
            throw new BaseException(ErrorCodeEnums.VIP_QUERY_LIST_SIZE_ERROR);
        }
        List<String> collect = dto.getMctNos().stream().map(QueryVipTagByMctNoDto::getMctNo).collect(Collectors.toList());
        List<QueryVipPublicTagInfoVo> res = bankPublicPrimitiveDao.queryVipTagByMcyNo(collect,CustomerTypeEnum.TYPE_PUBLIC.getValue());
        return  BaseResult.success(res);
    }

    @Override
    public BaseResult queryVipTagConfig(QueryVipTagConfigDto dto) {
        List<TagInfo> list = tagInfoDao.list(new LambdaQueryWrapper<TagInfo>()
                .eq(TagInfo::getTagStatus,StatusEnum.ENABLE.getValue()));
        List<QueryVipTagConfigVo> voList = new ArrayList<>();
        for (TagInfo tagInfo : list) {
            QueryVipTagConfigVo vipTagConfigVo = new QueryVipTagConfigVo();
            vipTagConfigVo.setId(tagInfo.getId() + "");
            vipTagConfigVo.setTagName(tagInfo.getTagName());
            vipTagConfigVo.setTagType(tagInfo.getTagType()+"");
            vipTagConfigVo.setTagDescription(tagInfo.getTagDescription());
            LocalDateTime updateTime = tagInfo.getUpdateTime();
            if (Objects.nonNull(updateTime)) {
                vipTagConfigVo.setUpdateTime(DateTimeUtil.localDateTimeToYYYY_MM_DD(updateTime));
            }
            vipTagConfigVo.setStatus(tagInfo.getTagStatus()+"");
            vipTagConfigVo.setTagPeopleNumber(tagInfo.getTagPeopleNumber()+"");
            voList.add(vipTagConfigVo);

        }
        return BaseResult.success(voList);
    }

    @Override
    public BaseResult queryVipTagConfig() {
        List<TagInfo> list = tagInfoDao.list(new LambdaQueryWrapper<TagInfo>()
                .eq(TagInfo::getTagStatus,StatusEnum.ENABLE.getValue()));
        List<QueryVipTagConfigVo> voList = new ArrayList<>();
        for (TagInfo tagInfo : list) {
            QueryVipTagConfigVo vipTagConfigVo = new QueryVipTagConfigVo();
            vipTagConfigVo.setId(tagInfo.getId() + "");
            vipTagConfigVo.setTagName(tagInfo.getTagName());
            vipTagConfigVo.setTagType(tagInfo.getTagType()+"");
            vipTagConfigVo.setTagDescription(tagInfo.getTagDescription());
            LocalDateTime updateTime = tagInfo.getUpdateTime();
            if (Objects.nonNull(updateTime)) {
                vipTagConfigVo.setUpdateTime(updateTime.toString());
            }
            vipTagConfigVo.setStatus(tagInfo.getTagStatus()+"");
            vipTagConfigVo.setTagPeopleNumber(tagInfo.getTagPeopleNumber()+"");
            voList.add(vipTagConfigVo);

        }
        return BaseResult.success(voList);
    }

    @Override
    public BaseResult queryVipTagConfigTzg() {
        List<TagInfo> list = tagInfoDao.list(new LambdaQueryWrapper<TagInfo>()
                .eq(TagInfo::getTagStatus,StatusEnum.ENABLE.getValue()));
        List<QueryVipTagConfigTZGVo> voList = new ArrayList<>();
        for (TagInfo tagInfo : list) {
            QueryVipTagConfigTZGVo vipTagConfigVo = new QueryVipTagConfigTZGVo();
            vipTagConfigVo.setId(tagInfo.getId() + "");
            vipTagConfigVo.setTagName(tagInfo.getTagName());
            vipTagConfigVo.setTagType(tagInfo.getTagType()+"");
            vipTagConfigVo.setTagDescription(tagInfo.getTagDescription());
            LocalDateTime updateTime = tagInfo.getUpdateTime();
            if (Objects.nonNull(updateTime)) {
                vipTagConfigVo.setUpdateTime(updateTime.toString());
            }
            vipTagConfigVo.setStatus(tagInfo.getTagStatus()+"");
            vipTagConfigVo.setTagPeopleNumber(tagInfo.getTagPeopleNumber()+"");
            vipTagConfigVo.setUpdateDate(tagInfo.getUpdateDate());
            voList.add(vipTagConfigVo);
        }
        return BaseResult.success(voList);
    }

    @Override
    public BaseResult queryVipGradeConfig(QueryVipGradeConfigDto dto) {
        List<VipGradeConfig> list = vipGradeConfigDao.list();
        List<QueryVipGradeConfigVo> voList = new ArrayList<>();
        list.forEach(vipGradeConfig -> {
            QueryVipGradeConfigVo gradeConfigVo = new QueryVipGradeConfigVo();
            gradeConfigVo.setId(vipGradeConfig.getId() + "");
            gradeConfigVo.setVipGrade(vipGradeConfig.getVipGrade() + "");
            gradeConfigVo.setVipName(vipGradeConfig.getVipName());
            gradeConfigVo.setGradeType(vipGradeConfig.getGradeType()+"");
            gradeConfigVo.setEquityDescription(vipGradeConfig.getEquityDescription());
            voList.add(gradeConfigVo);
        });
        return BaseResult.success(voList);
    }
    @Override
    public BaseResult queryVipGradeByIdCard(QueryVipGradeByIdCardListDto dto) {
        if (Objects.isNull(dto) || CollectionUtils.isEmpty(dto.getDtos())) {
            throw new BaseException(ErrorCodeEnums.PARAM_IS_NULL);
        }

        //限制每次查询最多1000条
        if (dto.getDtos().size()>1000){
            throw new BaseException(ErrorCodeEnums.VIP_QUERY_LIST_SIZE_ERROR);
        }
        List<QueryVipGradeByIdCardVo> voList = vipInfoDao.queryVipGradeByIdCard(dto.getDtos(),GradeTypeEnum.TYPE_PRIVATE.getValue());
        return BaseResult.success(voList);
    }

    @Override
    public BaseResult queryVipGradeByMctNo(QueryVipGradeByMctNoDtos dto) {
        if (Objects.isNull(dto) || CollectionUtils.isEmpty(dto.getMctNos())) {
            throw new BaseException(ErrorCodeEnums.PARAM_IS_NULL);
        }

        //限制每次查询最多1000条
        if (dto.getMctNos().size()>1000){
            throw new BaseException(ErrorCodeEnums.VIP_QUERY_LIST_SIZE_ERROR);
        }
        List<QueryVipGradeByMctVo> res = bankPublicPrimitiveDao.queryVipGradeByMctNo(dto.getMctNos(),GradeTypeEnum.TYPE_PUBLIC.getValue());
        return BaseResult.success(res);
    }

    @Override
    public BaseResult queryVipByCstNo(QueryVipByCstNoDto dto) {
        if (Objects.isNull(dto) || StringUtils.isEmpty(dto.getCstNo())) {
            throw new BaseException(ErrorCodeEnums.PARAM_IS_NULL);
        }
        VipInfo byCstId = vipInfoDao.getByCstId(dto.getCstNo());
        if (Objects.isNull(byCstId)){
            throw new BaseException(ErrorCodeEnums.VIP_IS_NOT_EXIST);
        }
        QueryVipByCstNoVo vo = new QueryVipByCstNoVo();
        vo.setIdCardNo(byCstId.getVipIdCardNo());
        return BaseResult.success(vo);
    }

    @Override
    public BaseResult queryVipGradeByCustomerNo(QueryVipGradeByCustomerDtos dto) {
        if (Objects.isNull(dto) || CollectionUtils.isEmpty(dto.getCustomerNos())) {
            throw new BaseException(ErrorCodeEnums.PARAM_IS_NULL);
        }

        //限制每次查询最多1000条
        if (dto.getCustomerNos().size()>1000){
            throw new BaseException(ErrorCodeEnums.VIP_QUERY_LIST_SIZE_ERROR);
        }
        List<QueryVipGradeByCustomerNoVo> res = vipInfoDao.queryVipGradeByCustomerNo(dto.getCustomerNos(),GradeTypeEnum.TYPE_PRIVATE.getValue());
        return BaseResult.success(res);
    }

    @Override
    public BaseResult queryVipTagByCustomerNo(QueryVipTagByCustomerNoListDto dto) {

        if (Objects.isNull(dto) || CollectionUtils.isEmpty(dto.getCustomerNos())) {
            throw new BaseException(ErrorCodeEnums.PARAM_IS_NULL);
        }
        //限制每次查询最多1000条
        if (dto.getCustomerNos().size()>1000){
            throw new BaseException(ErrorCodeEnums.VIP_QUERY_LIST_SIZE_ERROR);
        }

        List<QueryVipTagInfoVo> res = vipInfoDao.queryVipTagByCustomerNo(dto.getCustomerNos(),CustomerTypeEnum.TYPE_PRIVATE.getValue());
        return BaseResult.success(res);
    }

    @Override
    public BaseResult queryTaskList(QueryTaskListDto queryTaskListDto) {
        ArrayList<String> taskTags = new ArrayList<>();
        taskTags.add(TaskEnum.VIP_TAG_BIND.getTaskTag());
        taskTags.add(TaskEnum.MCT_TAG_BIND.getTaskTag());
        taskTags.add(TaskEnum.EDIT_VIP_RATING.getTaskTag());
        taskTags.add(TaskEnum.EDIT_MCT_RATING.getTaskTag());
        taskTags.add(TaskEnum.NEW_VIP_RATING.getTaskTag());
        taskTags.add(TaskEnum.NEW_MCT_RATING.getTaskTag());
        List<TaskInfo> list = taskInfoDao.list(new LambdaQueryWrapper<TaskInfo>()
                .in(TaskInfo::getTaskTag,taskTags));
        ArrayList<QueryTaskListVo> queryTaskListVos = new ArrayList<>();
        Integer VIP_RATING=0;
        Integer MCT_RATING=0;

        for (TaskInfo taskInfo : list) {
            QueryTaskListVo queryTaskListVo = new QueryTaskListVo();
            String taskTag = taskInfo.getTaskTag();
            Integer taskStatus = taskInfo.getTaskStatus();
            Integer taskLastExcuteDate = taskInfo.getTaskLastExcuteDate();
            if (TaskEnum.EDIT_VIP_RATING.getTaskTag().equals(taskTag)){
                LocalDate now = LocalDate.now();
                LocalDate taslDate = DateTimeUtil.parseYYYYMMDD(taskLastExcuteDate.toString())
                        .minusMonths(3);
//                20240811 20240820 20241111
                if (taslDate.compareTo(now)>= 0){
                    VIP_RATING= TaskStatusEnum.FAIL.getStatus();
                }
                continue;
            }else if (TaskEnum.EDIT_MCT_RATING.getTaskTag().equals(taskTag)){
                LocalDate now = LocalDate.now();
                LocalDate taslDate = DateTimeUtil.parseYYYYMMDD(taskLastExcuteDate.toString())
                        .minusMonths(1);
                if (taslDate.compareTo(now)>= 0){
                    MCT_RATING= TaskStatusEnum.FAIL.getStatus();
                }
                continue;
            }
            if (LocalDate.now().compareTo(DateTimeUtil.parseYYYYMMDD(taskLastExcuteDate.toString()))!= 0){
                taskStatus= TaskStatusEnum.FAIL.getStatus();
            }
            if (TaskEnum.NEW_VIP_RATING.getTaskTag().equals(taskTag)){
                VIP_RATING=TaskStatusEnum.FAIL.getStatus()==taskStatus?TaskStatusEnum.FAIL.getStatus():VIP_RATING;
                continue;
            }else if (TaskEnum.NEW_MCT_RATING.getTaskTag().equals(taskTag)){
                MCT_RATING=TaskStatusEnum.FAIL.getStatus()==taskStatus?TaskStatusEnum.FAIL.getStatus():MCT_RATING;
                continue;
            }
            queryTaskListVo.setTaskTag(taskTag);
            queryTaskListVo.setTaskStatus(taskStatus+"");
            queryTaskListVo.setTaskName(taskInfo.getTaskName()+"");
            queryTaskListVos.add(queryTaskListVo);
        }
        //等级任务必定成功
        VIP_RATING=0;
        MCT_RATING=0;
        {
            QueryTaskListVo queryTaskListVo = new QueryTaskListVo();
            queryTaskListVo.setTaskTag(TaskEnum.EDIT_VIP_RATING.getTaskTag());
            queryTaskListVo.setTaskStatus(VIP_RATING+"");
            queryTaskListVo.setTaskName(TaskEnum.EDIT_VIP_RATING.getTaskName());
            queryTaskListVos.add(queryTaskListVo);
        }
        {
            QueryTaskListVo queryTaskListVo = new QueryTaskListVo();
            queryTaskListVo.setTaskTag(TaskEnum.EDIT_MCT_RATING.getTaskTag());
            queryTaskListVo.setTaskStatus(MCT_RATING+"");
            queryTaskListVo.setTaskName(TaskEnum.EDIT_MCT_RATING.getTaskName());
            queryTaskListVos.add(queryTaskListVo);
        }
        return BaseResult.success(queryTaskListVos);
    }
}
